package br.com.android.financas.adapter;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.joda.time.DateTime;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.TextView;
import br.com.android.financas.MesTotal;
import br.com.android.financas.R;
import br.com.android.financas.model.Apresentavel;
import br.com.android.financas.model.Categoria;
import br.com.android.financas.model.Despesa;
import br.com.android.financas.model.Poupanca;
import br.com.android.financas.model.Receita;
import br.com.android.financas.repositorio.RepositorioDespesa;
import br.com.android.financas.repositorio.RepositorioPoupanca;
import br.com.android.financas.repositorio.RepositorioReceita;
import br.com.android.financas.repositorio.impl.RepositorioDespesaImpl;
import br.com.android.financas.repositorio.impl.RepositorioPoupancaImpl;
import br.com.android.financas.repositorio.impl.RepositorioReceitaImpl;

public class ListaDespesasMensaisAdapter extends BaseExpandableListAdapter {

    private Activity context;
    private Map<MesTotal, List<Apresentavel>> mesCollections;
    private List<MesTotal> meses;
    private int mesCorrente=0;
	private RepositorioDespesa repositorioDespesa;
	private RepositorioReceita repositorioReceita;
	private RepositorioPoupanca repositorioPoupanca;

    public ListaDespesasMensaisAdapter(Activity context, Map<MesTotal, List<Apresentavel>> mesesTotais) {
        this.context = context;
    	try {
			repositorioDespesa = new RepositorioDespesaImpl(context);
			repositorioReceita = new RepositorioReceitaImpl(context);
			repositorioPoupanca = new RepositorioPoupancaImpl(context);
		} catch (SQLException e) {
		}
        setMesesTotais(mesesTotais);
       // if(meses.size()>0)
        //	carregaItens(getGroup(mesCorrente),null);
    }

    public void setMesesTotais( Map<MesTotal, List<Apresentavel>> mesesTotais){
    	  meses=new ArrayList<MesTotal>();
          mesCollections=new LinkedHashMap<MesTotal, List<Apresentavel>>();

          List<MesTotal> ms=new ArrayList<MesTotal>(mesesTotais.keySet());
          Collections.sort(ms);
          Collections.reverse(ms);
          int i=0;
          DateTime hoje=new DateTime();
          for(MesTotal m:ms){
          	meses.add(m);
          	List<Apresentavel> tmps=mesesTotais.get(m);
          	Collections.sort(tmps);
          	Collections.reverse(tmps);


          	if(m.getMes().getMonthOfYear()==hoje.getMonthOfYear() && m.getMes().getYear()==hoje.getYear()){
          		mesCorrente=i;
          		//carregaItens(m,null);
          	}
          	mesCollections.put(m, tmps);
          	i++;
          }
    }

    public void carregaItens(MesTotal mes,Categoria categoria){
    	if(mes!=null){
	    	List<Despesa> despesas=new ArrayList<Despesa>();
	    	List<Receita> receitas=new ArrayList<Receita>();
	    	List<Poupanca> poupancas=new ArrayList<Poupanca>();

	    	if(categoria!=null && categoria.getId()!=null){
	    		despesas= repositorioDespesa.getDespesas(categoria,mes.getMes().toDate());
	    	}else{
	    		despesas= repositorioDespesa.getDespesas(mes.getMes().toDate());
	    		receitas= repositorioReceita.getReceitas(mes.getMes().toDate());
	    		poupancas= repositorioPoupanca.getDespesas(mes.getMes().toDate());
	    	}

			List<Apresentavel> lista=new ArrayList<Apresentavel>();
			lista.addAll(despesas);
			lista.addAll(receitas);
			lista.addAll(poupancas);
			Collections.sort(lista);
	      	Collections.reverse(lista);
	      	setChilds(mes, lista);
    	}
    }


    public void setChilds(MesTotal mes, List<Apresentavel> lista){
    	mesCollections.put(mes, lista);
    	notifyDataSetChanged();
    }

    public List<Apresentavel> getChildren(int groupPosition){
    	try{
    		return mesCollections.get(meses.get(groupPosition));
    	}catch(Exception e){
    		return Collections.emptyList();
    	}
    }

	public Apresentavel getChild(int groupPosition, int childPosition) {
        return mesCollections.get(meses.get(groupPosition)).get(childPosition);
    }

    public long getChildId(int groupPosition, int childPosition) {
        return childPosition;
    }

    public View getChildView(final int groupPosition, final int childPosition,
            boolean isLastChild, View convertView, ViewGroup parent) {
        final Apresentavel despesa = getChild(groupPosition, childPosition);
        LayoutInflater inflater = context.getLayoutInflater();

        if (convertView == null) {
            convertView = inflater.inflate(R.layout.despesa_item, null);
        }

        TextView descricao = (TextView) convertView.findViewById(R.listaItemDespesa.titulo);
        TextView dia = (TextView) convertView.findViewById(R.listaItemDespesa.dia);
        TextView valor = (TextView) convertView.findViewById(R.listaItemDespesa.valor);
        TextView categoria = (TextView) convertView.findViewById(R.listaItemDespesa.categoria);


        descricao.setText(despesa.getDescricao());
        dia.setText( (new DateTime(despesa.getData().getTime())).toString("dd"));
        valor.setText(NumberFormat.getCurrencyInstance().format(despesa.getValor()));
        categoria.setBackgroundColor(despesa.getCor());
        return convertView;
    }

    public int getChildrenCount(int groupPosition) {
    	try{
    		return mesCollections.get(meses.get(groupPosition)).size();
    	}
    	catch(Exception e){
    		return 0;
    	}

    }

    public MesTotal getGroup(int groupPosition) {
    	try{
    		return meses.get(groupPosition);
    	}catch(Exception e){
    		return null;
    	}
    }

    public int getGroupCount() {
        return meses.size();
    }

    public long getGroupId(int groupPosition) {
        return groupPosition;
    }

    public View getGroupView(int groupPosition, boolean isExpanded,
            View convertView, ViewGroup parent) {

        MesTotal mes = getGroup(groupPosition);
        if (convertView == null) {
            LayoutInflater infalInflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = infalInflater.inflate(R.layout.despesa_grupo_item,
                    null);
        }
        TextView item = (TextView) convertView.findViewById(R.linhaMes.titulo);
        TextView total = (TextView) convertView.findViewById(R.linhaMes.total);
        item.setTypeface(null, Typeface.BOLD);
        total.setTypeface(null,Typeface.ITALIC);
        if(mes.getMes().year().get()==(new DateTime().year().get()))
        	item.setText(mes.getMes().toString("MMMM"));
        else
        	item.setText(mes.getMes().toString("MMMM yyyy"));

        DecimalFormat formatter = (DecimalFormat)NumberFormat.getCurrencyInstance();
        String symbol = formatter.getCurrency().getSymbol();
        formatter.setNegativePrefix("- "+symbol); // or "-"+symbol if that's what you need
        formatter.setNegativeSuffix("");

        total.setText(formatter.format(mes.getTotal()));

        total.setTextColor(Color.parseColor("#008000"));
        if(mes.getTotal()<0)
        	total.setTextColor(Color.RED);

        return convertView;
    }

    public boolean hasStableIds() {
        return true;
    }

    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return true;
    }

    public int getMesCorrente(){
    	return mesCorrente;
    }
}